<!--注册 页面-->
<template>

  <div id="register">
    <el-row>
      <el-col :span="20" :offset="12">
        <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

          <el-form-item label="头像" prop="face" >
            <uploadCard
              @func="getImgUrl" ref="uploadCard"
              upType="选取头像"
              :listType="uploadParam.LIST_TYPE_PICTURE_CARD"
              :tip="uploadParam.TIP_PICTURE"
              :limit="1"
              :imgFlag="user.imgFlag"
            ></uploadCard>
          </el-form-item>

          <el-form-item label="帐号" prop="account" >
            <el-input v-model="ruleForm.account" :disabled="user.accountFlag"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="mail">
            <el-input  type = "mail" v-model="ruleForm.mail" ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="user.passwordFlag" >
            <el-input type="password" v-model="ruleForm.password" ></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass" v-if="user.checkPassFlag">
            <el-input type="password" v-model="ruleForm.checkPass" ></el-input>
          </el-form-item>
          <el-form-item label="昵称" prop="nickName" >
            <el-input v-model="nickName" ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="danger" @click="submitForm('ruleForm','add')" v-if="user.registerFlag">注册</el-button>
            <router-link to="/login">
            <el-button type="success" v-if="user.loginFlag">登陆</el-button>
            </router-link>
            <router-link to="/">
              <el-button type="" v-if="user.homeFlag">主页</el-button>
            </router-link>
            <el-button type="primary" @click="submitForm('ruleForm','update')" v-if="user.saveFlag">保存</el-button>
            <el-button type="" @click="resetForm('ruleForm')" >返回</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>

</template>
<script>
  import uploadCard from '@/components/UploadCard'
  import {UploadParam} from "../../constant/UploadParam";
  import {User} from "../req/User";
  import {Handle} from "../../constant/Handle";
  import {ResultStatus} from "../../constant/ResultStatus";
  import {StringUtil} from "../../../utils/StringUtil";
  import {ContentType} from "../../constant/ContentType";
  let user = new User();
  export default {
    data() {

      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm.checkPass !== '') {
            this.$refs.ruleForm.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      //邮箱规则
      var mailRul = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,10})$/;
      var mail = (rule,value,callback) => {
        if(value === ''){
          callback(new Error('请输入邮箱'));
        }

        if(!mailRul.test(value)){
          callback(new Error('邮箱格式不正确'))
        }
        callback();
      };
      //帐户规则
      var accountRul = /^[a-zA-Z0-9]{6,}$/
      var account = (rule,value,callback) => {
        if(value === ''){
          callback (new Error('请输入帐号'));
        }
        if(!accountRul.test(value)){
          callback(new Error('帐户必须是6位以上的数字或字母'))
        }

        callback();
      }
      return {
        ruleForm: {
          password: '',
          checkPass: '',
          account:'',
          mail:''
        },
        rules: {
          password: [
            { validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            { validator: validatePass2, trigger: 'blur' }
          ],
          mail:[
            {validator:mail,trigger:'blur'}
          ],
          account:[
            {validator:account,trigger:'blur'}
          ]

        },
        uploadParam: UploadParam,
        verifyFlag:true,
        type:this.$route.query.type,
        handle:this.$route.query.handle,
        adminFlag:this.$route.query.adminFlag,
        user:user,
        id:this.$route.query.id,
        nickName:'',
      };
    },
    methods: {
      submitForm:async function(formName,handler) {
        this.$refs[formName].validate((valid) => {
          if (!valid) {
            this.$notify(StringUtil.warning("错误提交，请检查输入"))
            this.verifyFlag = false;
            return false;
          }
        });
        if (!this.verifyFlag) {
          return;
        }
        //调用上传组件的方法
        await this.$refs.uploadCard.submitUpload();

        this.user.handle = handler;
        this.user.password = this.ruleForm.password;
        this.user.mail = this.ruleForm.mail;
        this.user.nickName = this.nickName;
        if(handler==Handle.ADD){
          this.user.id = this.ruleForm.account;
        }
        if(handler == Handle.UPDATE){
          this.user.id = this.id;
        }

        this.$axios({
          method: 'post',
          url: 'user/save',
          data: JSON.stringify(this.user),
          datatype: 'json',
          headers: {
            'content-type': 'application/json;charset=UTF-8'
          },
        }).then((response) => {

          let datas = response.data;
          if (datas.code == ResultStatus.SUCCESS) {
            this.$notify(StringUtil.success(datas.msg));

            if(this.adminFlag) {
              this.$router.push({path: '/admin/user'})
            }
            else{
              this.$router.push({path:'/login'})
            }
          } else {
            this.$notify(StringUtil.warning(datas.msg));
            return;
          }

        }).catch(function (error) {
          console.log(error)
          alert(error.data.msg);
          return false;
        });

      },
      resetForm(formName) {
        if(this.adminFlag) {
          this.$router.push({name: 'user'})
        }
        else{
          this.$router.push({name:"home"})
        }

      },
      initComponent(){
        this.user = new User();

        //后台没有登陆
        //前台没有保存
        if(this.adminFlag) {
          this.user.loginFlag = false;
          this.user.homeFlag = false;
        }
        else{
          this.user.saveFlag = false;

          //this.user.returnFlag = false;
        }

        switch (this.handle) {
          case Handle.QUERY:
            this.user.saveFlag=false;
            this.user.registerFlag=false;
            break;
          case Handle.UPDATE:
            this.user.registerFlag = false;
            this.user.accountFlag=true;
            this.user.saveFlag=true;
            break;
          case Handle.DEL:
            break;
          case Handle.ADD:
            this.user.saveFlag = false;
            break;
          default:
            break;

        }





      },
      /**
       * 获取上传组件的回传url
       * @param data
       */
      getImgUrl: function (data) {

        this.user.face = data;

      },
      /**
       * 查看用户
       */
      getUser(){
        let user = new User();
        user.handle = Handle.QUERY;
        user.id = this.id;

        this.$axios
          .post('/user/save',
            user, //转成json
            ContentType.APPLICATION_JSON,
          )
          .then((response) => {

            let datas = response.data;
            if (datas.code != ResultStatus.SUCCESS) {
              this.$notify(StringUtil.warning(datas.msg));
              return;
            }
            user = datas.data;
            this.ruleForm.account = user.id;
            this.ruleForm.mail = user.mail;
            this.nickName = user.nickName;
            this.ruleForm.password= user.password;
            this.ruleForm.checkPass = user.password;
            //调取图片组件的方法
            this.$refs.uploadCard.receiveFileList(user.face);

          })
          .catch((error) => {
            console.log(error);
            let datas = error.data;
            this.$notify(StringUtil.warning(datas.msg));
          })
      }

    },
    components:{
      uploadCard,
    },
    mounted : async function() {
      if(this.adminFlag) {
        this.getUser();
      }
      this.initComponent();


    }
  }
</script>

<style>
  #register{
    width: 50%  }
</style>
